package edu.polsl.bio.tools.alignment;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.polsl.bio.tools.util.Utils;

/**
 * //todo class description
 * <p/>
 * Created on: Aug 31, 2010 11:40:10 AM <br/>
 * <a href="http://www.polsl.pl">www.polsl.pl</a>
 *
 * @author lukasz.olczak@polsl.pl
 */
public class LightWeightAligner {
  /**
   * slf4j Logger.
   */
  private static final Logger log = LoggerFactory.getLogger(LightWeightAligner.class.getName());

  private int refLength;

  //should be positive
  private int match;

  //should be negative
  private int mismatch;

  //should be positive
  private int indel;

  private int[][] tab;

  public LightWeightAligner(int size, int match, int mismatch, int indel) {
    refLength = size;
    this.match = match;
    this.mismatch = mismatch;
    this.indel = indel;
    init();
  }

  private void init() {
    tab = new int[2][refLength + 1];
  }

  public int align(String refSeq, String querySeq) {
    tab[0][0] = 0;
    for (int i = 1; i <= refSeq.length() - 1; i++) {
      tab[0][i] = -i * indel;
    }
    int left = 0;
    int right = 0;
    for (int i = 0; i < querySeq.length(); i++) {
      left = i % 2;
      right = (i + 1) % 2;
      tab[right][0] = -(i + 1) * indel;
      for (int j = 1; j <= refSeq.length(); j++) {
        int ul = (refSeq.charAt(j - 1) == querySeq.charAt(i) ? match : mismatch) + tab[left][j - 1];
        int l = tab[left][j] - indel;
        int u = tab[right][j - 1] - indel;
        tab[right][j] = Utils.max(ul, l, u);
      }
    }

    return tab[right][refSeq.length()];
  }

}
